package com.ete.service.dialog.version

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.ete.service.callback.version.DownloadListener
import com.ete.service.dialog.BaseDialog
import com.ete.service.entry.dialog.CommonDialogEntry
import com.ete.service.entry.version.VersionEntry
import com.ete.service.entry.version.VersionUpgradeInfo
import com.ete.service.manager.ManagerConstant
import com.ete.service.manager.version.VersionManager
import com.ete.service.service.R
import com.ete.service.service.databinding.DialogUpgradeVersionBinding
import com.ete.service.service.version.VersionHelper
import com.ete.service.service.version.sp.VersionSpUtil
import com.ete.service.util.AESUtil
import com.ete.service.util.DownloadUtil
import com.ete.service.util.log.EteLog
import java.io.File

/**
 * Author:LiXian
 * <p>
 * Desc:升级版本
 * Version:1.0
 * date 2023/12/20 9:07
 */
class UpgradeVersionDialog(
        var mContext: Context,
        var mVersionEntry: VersionEntry,
        var mUpgradeInfo: VersionUpgradeInfo,
        var mCancelCallback: (() -> Unit)? = null
) : BaseDialog(mContext, R.style.XUIDialog_Custom) {

    private var isUpgrading = false
    private var isDownloaded = false

    private val mBinding = DialogUpgradeVersionBinding.inflate(LayoutInflater.from(mContext))

    private val mApkPath: String by lazy {
        "${mVersionEntry.mAppPathDir}/V${mUpgradeInfo.version}.apk"
    }

    fun initDialog() {
        setCanceledOnTouchOutside(false)
        setCancelable(false)
        setContentView(mBinding.root)
        initView()
        checkDownloadComplete()
    }

    private fun initView() {
        mBinding.dialogBtnCancel.updateNormalBgColor(R.color.color_E7EAF2)
        if (mVersionEntry.mAppThemeColor == 0) {
            mBinding.dialogClContainer.updateGradientBg(R.color.color_3F73ED)
            mBinding.dialogBtnUpgrade.updateNormalBgColor(R.color.color_3F73ED)
            mBinding.dialogBtnNotice.updateNormalBgColor(R.color.color_3F73ED)
        } else {
            mBinding.dialogClContainer.updateGradientBg(mVersionEntry.mAppThemeColor)
            mBinding.dialogBtnUpgrade.updateNormalBgColor(mVersionEntry.mAppThemeColor)
            mBinding.dialogBtnNotice.updateNormalBgColor(mVersionEntry.mAppThemeColor)
        }
        mBinding.mVersionInfo = mUpgradeInfo
        mBinding.dialogBtnCancel.setOnClickListener {
            VersionSpUtil.putNoticeUpgradeDate()
            dismissDialog()
        }
        mBinding.dialogIvClose.setOnClickListener {
            VersionSpUtil.putNoticeUpgradeDate()
            dismissDialog()
        }
        mBinding.dialogBtnNotice.setOnClickListener {
            VersionSpUtil.putNotNoticeVersion(mUpgradeInfo.version ?: "")
            dismissDialog()
        }
        mBinding.dialogBtnUpgrade.setOnClickListener {
            if (isDownloaded) installNewApk() else downloadNewApk()
        }
        //静默安装，强制升级
//        if (mVersionEntry.isSilentInstall) {
//            mBinding.dialogBtnCancel.visibility = View.GONE
//            mBinding.dialogIvClose.visibility = View.GONE
//            mBinding.dialogBtnNotice.visibility = View.GONE
//        } else {
            //非静默安装，根据类型提示
            when (mUpgradeInfo.releaseType) {
                ManagerConstant.RELEASE_TYPE_VERSION_FORCE -> {
                    mBinding.dialogBtnCancel.visibility = View.GONE
                    mBinding.dialogIvClose.visibility = View.GONE
                    mBinding.dialogBtnNotice.visibility = View.GONE
                }

                ManagerConstant.RELEASE_TYPE_VERSION_STRONG -> {
                    mBinding.dialogBtnCancel.visibility = View.VISIBLE
                    mBinding.dialogIvClose.visibility = View.VISIBLE
                    mBinding.dialogBtnNotice.visibility = View.VISIBLE
                }

                ManagerConstant.RELEASE_TYPE_VERSION_WEAK -> {
                    mBinding.dialogBtnCancel.visibility = View.VISIBLE
                    mBinding.dialogIvClose.visibility = View.VISIBLE
                    mBinding.dialogBtnNotice.visibility = View.GONE
                }
            }
//        }
    }

    private fun checkDownloadComplete() {
        val isExists = FileUtils.isFileExists(mApkPath)
        val mFileMD5 = FileUtils.getFileMD5ToString(mApkPath)
        if (isExists) {
            val isEqualsMD5 = mFileMD5.equals(mUpgradeInfo.fileMd5, true)
            if (isEqualsMD5) {
                isDownloaded = true
                if (mVersionEntry.isSilentInstall) {
                    mBinding.dialogBtnUpgrade.text = mContext.getString(R.string.version_installing)
                    installNewApk()
                } else {
                    mBinding.dialogBtnUpgrade.text = mContext.getString(R.string.version_download_complete)
                }
                EteLog.d("新版Apk下载完成，mApkPath:[${mApkPath}] mUpgradeInfo:[${mUpgradeInfo}]")
            } else {
                EteLog.d("新版Apk已存在，但MD5不相等删除文件，mFileMD5:[$mFileMD5] mApkPath:[${mApkPath}] mUpgradeInfo:[${mUpgradeInfo}]")
                FileUtils.delete(mApkPath)
            }
        } else {
            EteLog.d("未下载新版Apk mUpgradeInfo:[${mUpgradeInfo}]")
        }
    }

    private fun dismissDialog() {
        if (isUpgrading) {
            ToastUtils.showShort(R.string.version_upgrading)
        } else {
            dismiss()
            mCancelCallback?.invoke()
        }
    }

    private fun downloadNewApk() {
        if (isUpgrading) {
            ToastUtils.showShort(R.string.version_upgrading)
            return
        }
        isUpgrading = true
        val apkUrl = AESUtil.decrypt(mUpgradeInfo.url, ManagerConstant.APK_URL_SECRET_KEY)
        DownloadUtil.download(apkUrl, mApkPath, object : DownloadListener {
            override fun onStart() {
                mBinding.dialogBtnUpgrade.text = mContext.getString(R.string.version_downloading, 0)
                mBinding.dialogBtnUpgrade.updateProgress(0)
            }

            override fun onProgress(totalBytes: Long, downloadBytes: Long, progress: Int) {
                mBinding.dialogBtnUpgrade.text = mContext.getString(R.string.version_downloading, progress)
                mBinding.dialogBtnUpgrade.updateProgress(progress)
            }

            override fun onFinish(file: File) {
                isUpgrading = false
                isDownloaded = true
                if (mVersionEntry.isSilentInstall) {
                    mBinding.dialogBtnUpgrade.text = mContext.getString(R.string.version_installing)
                    installNewApk()
                } else {
                    mBinding.dialogBtnUpgrade.text = mContext.getString(R.string.version_download_complete)
                }
            }

            override fun onFail(errorMessage: String) {
                ToastUtils.showShort(errorMessage)
                mBinding.dialogBtnUpgrade.text = mContext.getString(R.string.version_restart)
                if (mVersionEntry.mAppThemeColor == 0) {
                    mBinding.dialogBtnUpgrade.updateNormalBgColor(R.color.color_3F73ED)
                } else {
                    mBinding.dialogBtnUpgrade.updateNormalBgColor(mVersionEntry.mAppThemeColor)
                }
                FileUtils.delete(mApkPath)
                isUpgrading = false
                isDownloaded = false
            }
        })
    }

    private fun installNewApk() {
        if (VersionHelper.isInstallPermission()) {
            EteLog.d(VersionManager.TAG, "下载APK路径mApkPath:[$mApkPath]")
            VersionManager.installApp(mApkPath)
        } else {
            val mCommonDialogEntry = CommonDialogEntry(
                    mContext,
                    mContext.getString(R.string.version_install_permission),
                    mContext.getString(R.string.version_install_permission_tip),
                    mContext.getString(R.string.version_next),
                    mContext.getString(R.string.version_cancel),
                    mVersionEntry.mAppThemeColor,
                    isShowLoading = false,
                    isShowSure = true,
                    isShowCancel = false,
                    isShowClose = true,
                    mSureCallback = {
                        VersionManager.installApp(mApkPath)
                        true
                    }
            )
            VersionHelper.showCommonDialog(mCommonDialogEntry).show()
        }
    }

    override fun getDialogWidthRate(): Float = 0.60F
}